<script setup>
import { ref, onMounted, onUnmounted, reactive } from 'vue'
import { ElProgress, ElCard, ElMessage } from 'element-plus'
import websocketService from '../utils/websocketService.js'

// 设备状态数据
const cpuUsage = ref(0)
const memoryUsage = ref(0)
const diskUsage = ref(0)
const euConnectionStatus = ref('normal') // normal, disconnected
const gpsStatus = ref('normal') // normal, searching

// 状态文本
const euStatusText = ref('连接正常')
const gpsStatusText = ref('定位正常')

// 设备详细信息
const deviceDetails = reactive({
  deviceName: '基站服务器-01',
  ipAddress: '192.168.1.100',
  uptime: '12小时30分钟',
  systemVersion: 'Ubuntu 20.04 LTS',
  cpuTemperature: '45°C',
  fanSpeed: '2200 RPM',
  uploadSpeed: '上行: 12.5 MB/s',
  downloadSpeed: '下行: 35.8 MB/s'
})

// 连接状态
const connectionStatus = ref('disconnected') // connected, disconnected, connecting

// WebSocket事件处理函数
function handleWebSocketOpen() {
  connectionStatus.value = 'connected'
  console.log('WebSocket连接成功，开始接收设备状态数据')
  ElMessage.success('设备状态实时更新已开启')
}

function handleWebSocketClose() {
  connectionStatus.value = 'disconnected'
  console.log('WebSocket连接关闭')
  ElMessage.warning('设备状态实时更新已停止')
}

function handleWebSocketError(error) {
  console.error('WebSocket连接错误:', error)
  ElMessage.error('设备状态更新连接异常')
}

// 处理接收到的设备状态数据
function handleDeviceStatusData(data) {
  // 确保数据有效
  if (!data || typeof data !== 'object') {
    console.warn('接收到无效的设备状态数据:', data)
    return
  }

  // 更新设备状态数据
  if (data.cpuUsage !== undefined) {
    cpuUsage.value = data.cpuUsage
  }
  
  if (data.memoryUsage !== undefined) {
    memoryUsage.value = data.memoryUsage
  }
  
  if (data.diskUsage !== undefined) {
    diskUsage.value = data.diskUsage
  }
  
  if (data.euConnectionStatus !== undefined) {
    euConnectionStatus.value = data.euConnectionStatus
    euStatusText.value = data.euConnectionStatus === 'normal' ? '连接正常' : '连接断开'
  }
  
  if (data.gpsStatus !== undefined) {
    gpsStatus.value = data.gpsStatus
    gpsStatusText.value = data.gpsStatus === 'normal' ? '定位正常' : '搜索中'
  }

  // 更新设备详细信息（如果有）
  if (data.details) {
    updateDeviceDetails(data.details)
  }
}

// 更新设备详细信息
function updateDeviceDetails(details) {
  if (details.deviceName) deviceDetails.deviceName = details.deviceName
  if (details.ipAddress) deviceDetails.ipAddress = details.ipAddress
  if (details.uptime) deviceDetails.uptime = details.uptime
  if (details.systemVersion) deviceDetails.systemVersion = details.systemVersion
  if (details.cpuTemperature) deviceDetails.cpuTemperature = details.cpuTemperature
  if (details.fanSpeed) deviceDetails.fanSpeed = details.fanSpeed
  if (details.uploadSpeed) deviceDetails.uploadSpeed = `上行: ${details.uploadSpeed}`
  if (details.downloadSpeed) deviceDetails.downloadSpeed = `下行: ${details.downloadSpeed}`
}

// 初始化WebSocket连接
function initWebSocket() {
  connectionStatus.value = 'connecting'
  
  // 注册事件监听器
  websocketService.on('open', handleWebSocketOpen)
  websocketService.on('close', handleWebSocketClose)
  websocketService.on('error', handleWebSocketError)
  websocketService.on('message:device-status', handleDeviceStatusData)
  websocketService.on('message', (data) => {
    console.log('接收到WebSocket消息:', data)
  })
  
  // 连接WebSocket服务器
  websocketService.connect()
}

// 清理WebSocket连接
function cleanupWebSocket() {
  // 移除事件监听器
  websocketService.off('open', handleWebSocketOpen)
  websocketService.off('close', handleWebSocketClose)
  websocketService.off('error', handleWebSocketError)
  websocketService.off('message:device-status', handleDeviceStatusData)
  
  // 关闭连接
  websocketService.close()
}

// 组件挂载时初始化WebSocket
onMounted(() => {
  // 设置模拟数据作为初始值
  cpuUsage.value = Math.floor(Math.random() * 20) + 10
  memoryUsage.value = Math.floor(Math.random() * 30) + 40
  diskUsage.value = Math.floor(Math.random() * 20) + 60
  
  // 初始化WebSocket连接
  initWebSocket()
})

// 组件卸载时清理WebSocket
onUnmounted(() => {
  cleanupWebSocket()
})
</script>

<template>
  <div class="device-management">
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <!-- CPU使用率 -->
      <el-col :span="5">
        <ElCard class="stats-card">
          <div style="margin-bottom: 10px; font-weight: bold;">CPU使用率</div>
          <ElProgress :percentage="cpuUsage" status="active" />
          <div style="margin-top: 10px; font-size: 16px;">{{ cpuUsage }}%</div>
        </ElCard>
      </el-col>
      
      <!-- 内存使用率 -->
      <el-col :span="5">
        <ElCard class="stats-card">
          <div style="margin-bottom: 10px; font-weight: bold;">内存使用率</div>
          <ElProgress :percentage="memoryUsage" status="active" />
          <div style="margin-top: 10px; font-size: 16px;">{{ memoryUsage }}%</div>
        </ElCard>
      </el-col>
      
      <!-- 磁盘空间 -->
      <el-col :span="5">
        <ElCard class="stats-card">
          <div style="margin-bottom: 10px; font-weight: bold;">磁盘空间</div>
          <ElProgress :percentage="diskUsage" status="active" />
          <div style="margin-top: 10px; font-size: 16px;">{{ diskUsage }}%</div>
        </ElCard>
      </el-col>
      
      <!-- EU连接状态 -->
        <el-col :span="4">
          <ElCard class="stats-card">
            <div style="margin-bottom: 10px; font-weight: bold;">EU连接状态</div>
            <div style="display: flex; align-items: center; justify-content: center;">
              <span 
                class="status-indicator"
                :class="euConnectionStatus === 'normal' ? 'status-running' : 'status-error'"
              ></span>
              <span>{{ euStatusText }}</span>
            </div>
          </ElCard>
        </el-col>
        
        <!-- GPS状态 -->
        <el-col :span="4">
          <ElCard class="stats-card">
            <div style="margin-bottom: 10px; font-weight: bold;">GPS状态</div>
            <div style="display: flex; align-items: center; justify-content: center;">
              <span 
                class="status-indicator"
                :class="gpsStatus === 'normal' ? 'status-running' : 'status-idle'"
              ></span>
              <span>{{ gpsStatusText }}</span>
            </div>
          </ElCard>
        </el-col>
    </el-row>
    
    <!-- 连接状态指示 -->
    <div style="margin-bottom: 15px; padding: 10px; border-radius: 5px; background-color: #f5f7fa; border-left: 4px solid;" :style="{ 'border-color': connectionStatus === 'connected' ? '#67c23a' : connectionStatus === 'connecting' ? '#e6a23c' : '#f56c6c' }">
      <span style="margin-right: 8px;">
        {{ connectionStatus === 'connected' ? '● 已连接' : connectionStatus === 'connecting' ? '● 连接中' : '● 未连接' }}
      </span>
      <span>{{ connectionStatus === 'connected' ? '设备状态实时更新中' : connectionStatus === 'connecting' ? '正在建立实时连接...' : '无法接收实时更新' }}</span>
    </div>

    <!-- 详细信息区域 -->
    <div class="form-section">
      <h3 style="margin-bottom: 20px;">设备详细信息</h3>
      
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form label-width="100px">
            <el-form-item label="设备名称">
              <el-input v-model="deviceDetails.deviceName" disabled style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="IP地址">
              <el-input v-model="deviceDetails.ipAddress" disabled style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="运行时长">
              <el-input v-model="deviceDetails.uptime" disabled style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="系统版本">
              <el-input v-model="deviceDetails.systemVersion" disabled style="width: 200px;"></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        
        <el-col :span="12">
          <el-form label-width="100px">
            <el-form-item label="CPU温度">
              <el-input v-model="deviceDetails.cpuTemperature" disabled style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="风扇转速">
              <el-input v-model="deviceDetails.fanSpeed" disabled style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="上传速度">
              <el-input v-model="deviceDetails.uploadSpeed" disabled style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="下载速度">
              <el-input v-model="deviceDetails.downloadSpeed" disabled style="width: 200px;"></el-input>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<style scoped>
.device-management {
  height: 100%;
  overflow: hidden;
  padding: 20px;
}

/* 确保统计卡片区域不会出现滚动条 */
.el-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

/* 调整卡片高度和内部元素布局 */
.stats-card {
  height: 100%;
  min-height: 120px;
}

/* 确保卡片内容能够撑满整个卡片 */
.stats-card :deep(.el-card__body) {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

/* 进度条颜色自定义 */
:deep(.el-progress-bar__inner) {
  background-color: #409eff;
}

/* 卡片样式调整 */
:deep(.el-card) {
  height: 100%;
  transition: all 0.3s ease;
}

:deep(.el-card:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 统计卡片内边距调整 */
:deep(.el-card__body) {
  padding: 15px;
}

/* 布局响应式调整 */
@media (max-width: 1200px) {
  .el-row {
    display: flex;
    flex-wrap: wrap;
  }
  
  .el-col {
    margin-bottom: 20px;
  }
}
</style>